package com.xudu.service.aop;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xudu.common.LogAnnotation;
import com.xudu.entity.Log;
import com.xudu.service.ILogService;
import com.xudu.utils.IpUtil;
import lombok.Builder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * ClassName: LogsAspect
 * Description:
 *
 * @Author xudu
 * @Create 2024/4/20
 */
@Builder
@Component
@Aspect
@Slf4j
public class LogsAspect {

    @Autowired
    private ILogService iLogService;

    @AfterReturning(pointcut = "@annotation(logAnnotation)", returning = "jsonResult")
    public void recordLog(JoinPoint joinPoint, LogAnnotation logAnnotation,Object jsonResult) throws JsonProcessingException {

        //获取httpservletRequest对象
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();

        //获取IP信息
        String ipAddr = IpUtil.getIpAddr(request);

        //获取请求参数和返回参数
        Object[] args = joinPoint.getArgs();
        // 入参数
        String params = com.alibaba.fastjson.JSON.toJSONString(args);
        //出参
        String result = com.alibaba.fastjson.JSON.toJSONString(jsonResult);


        //组装实体对象
        Log build = Log.builder()
                .operation(logAnnotation.operation())
                .type(logAnnotation.type().getValue())
                .ip(ipAddr)
                .time(DateUtil.now())
                .url(request.getRequestURL().toString())
                .method(request.getMethod())
                .requestparam(params)
                .resultparam(result)
                .build();

        System.out.println(build);
        //将数据保存到数据库中
        iLogService.save(build);

    }
}
